package ycl.common.utils;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ycl.common.base.entity.BaseEntity;
import ycl.common.models.BaseEntityRes;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 基类工具
 *
 * @author ycl
 * @date 2022/6/23 0023 20:48:28
 */
public class BaseEntityUtil {

	/**
	 * 查看此实体类有没有某个字段
	 *
	 * @param <T> 实体类
	 * @return
	 */
	public static <T extends BaseEntity> boolean hasField(Class<T> c, String field) {
		if (c == null)
			return false;
		Class<?> p = c;
		do {
			Field[] fields = p.getDeclaredFields();
			if (fields.length != 0) {
				for (Field f : fields)
					if (f.getName().equals(field))
						return true;
			}
		} while ((p = p.getSuperclass()) != null);
		return false;
	}


	/**
	 * 分页数据类型转化
	 *
	 * @param page
	 * @param c
	 * @param <T>
	 * @param <R>
	 * @return
	 */
	@SuppressWarnings("all")
	public static <T extends BaseEntity, R extends BaseEntityRes> Page<R> pageCast(Page<T> page, Class<R> c) {
		if (page == null)
			return new Page<>();
		List<T> records = page.getRecords();
		page.setRecords(null);
		Page<R> res = (Page<R>) JSONObject.parseObject(JSONObject.toJSONString(page), Page.class);
		if (CollUtil.isNotEmpty(records)) {
			List<R> rs = BeanConvertUtil.convertList(records, c);
			res.setRecords(rs);
		}
		return res;
	}

	/**
	 * 数据表实体转换成可返回给前端的类型
	 *
	 * @param t
	 * @param r
	 * @param <T>
	 * @param <R>
	 * @return
	 */
	public static <T extends BaseEntity, R extends BaseEntityRes> R cast(T t, Class<R> r) {
		if (t == null)
			return null;
		return BeanConvertUtil.convert(t, r);
	}
}
